<template>
  <div>
    <div class="bg-white border-bottom mb-1">
      <div class="log-select"
           @click="showPopup">
        <text class="log-select-label">批次查询</text>
        <text class="log-select-content"
              :class="[!columnSelected.enter_batch_no && 'text-muted']">{{columnSelected.enter_batch_no || '选择批次'}}</text>
        <text class="icon log-select-icon">&#xe69b;</text>
      </div>

      <div class="flex-row pb-2"
           v-if="columnSelected.enter_batch_no">
        <div class="flex align-center">
          <text class="log-num">{{columnSelected.day_age || '-'}}</text>
          <text class="log-hint">日龄(天)</text>
        </div>
        <div class="flex align-center">
          <text class="log-num">{{columnSelected.chick_amount || '-'}}</text>
          <text class="log-hint">入栏总数(羽)</text>
        </div>
        <div class="flex align-center">
          <text class="log-num">{{columnSelected.sur_rate || '-'}}</text>
          <text class="log-hint">存活率(%)</text>
        </div>
      </div>
    </div>

    <wxc-tab-page ref="wxc-tab-page"
                  :tab-titles="tabTitles"
                  :tab-styles="tabStyles"
                  :tab-page-height="tabPageHeight"
                  title-type="text">
      <div class="container">
        <div class="td-row">
          <text class="td-serial text-muted">栋号</text>
          <text class="td-text text-muted">时间</text>
          <text class="td-text text-muted">死鸡数</text>
          <text class="td-text text-muted">淘汰数</text>
          <text class="td-text text-muted">投料类</text>
          <text class="td-text text-muted"
                v-if="isEggChick">产蛋数</text>
          <text class="td-text text-muted"
                v-if="isEggChick">异蛋数</text>
        </div>

        <vm-status v-if="showLogStatus"
                   empty-text="暂无日志"
                   :type="logTotalPages === -1 ? 'error' : 'empty'"></vm-status>

        <list ref="logList"
              :showRefresh="true"
              :showLoadMore="showLogLoadMore"
              @refresh="logRefresh('logList')"
              @loadMore="logLoadmore('logList')"
              loadmoreoffset="100">
          <cell v-for="(log, index) in logs"
                :key="index">
            <div class="td-row">
              <text class="td-serial">{{log.house_no}}</text>
              <text class="td-text">{{log.log_time}}</text>
              <text class="td-text">{{log.die_num}}</text>
              <text class="td-text">{{log.eli_num || '-'}}</text>
              <text class="td-text">{{log.feed_product_name || '-'}}</text>
              <text class="td-text"
                    v-if="isEggChick">{{log.egg_num || '-'}}</text>
              <text class="td-text"
                    v-if="isEggChick">{{log.ex_egg_num || '-'}}</text>
            </div>
          </cell>
        </list>
      </div>

      <div class="container">
        <div class="td-row">
          <text class="td-serial text-muted">栋号</text>
          <text class="td-text text-muted">时间</text>
          <text class="td-text text-muted">免疫类</text>
          <text class="td-text text-muted">免疫用量</text>
          <text class="td-text text-muted">用药类</text>
          <text class="td-text text-muted">用药用量</text>
        </div>

        <vm-status v-if="showLogStatus"
                   empty-text="暂无日志"
                   :type="logTotalPages === -1 ? 'error' : 'empty'"></vm-status>

        <list ref="diList"
              :showRefresh="true"
              :showLoadMore="showLogLoadMore"
              @refresh="logRefresh('diList')"
              @loadMore="logLoadmore('diList')"
              loadmoreoffset="100">
          <cell v-for="(log, index) in logs"
                :key="index">
            <div class="td-row">
              <text class="td-serial">{{log.house_no}}</text>
              <text class="td-text">{{log.log_time}}</text>
              <text class="td-text">{{log.imm_product_name}}</text>
              <text class="td-text">{{log.imm_dosage || '-'}}</text>
              <text class="td-text">{{log.drug_product_name || '-'}}</text>
              <text class="td-text">{{log.drug_product_amount || '-'}}</text>
            </div>
          </cell>
        </list>
      </div>

      <div class="container">
        <div class="td-row">
          <text class="td-serial text-muted">栋号</text>
          <text class="td-text text-muted">时间</text>
          <text class="td-text text-muted">均温度</text>
          <text class="td-text text-muted">均湿度</text>
        </div>

        <vm-status v-if="showLogStatus"
                   empty-text="暂无日志"
                   :type="logTotalPages === -1 ? 'error' : 'empty'"></vm-status>

        <list ref="thList"
              :showRefresh="true"
              :showLoadMore="showLogLoadMore"
              @refresh="logRefresh('thList')"
              @loadMore="logLoadmore('thList')"
              loadmoreoffset="100">
          <cell v-for="(log, index) in logs"
                :key="index">
            <div class="td-row">
              <text class="td-serial">{{log.house_no}}</text>
              <text class="td-text">{{log.log_time}}</text>
              <text class="td-text">{{log.temperature}}</text>
              <text class="td-text">{{log.humidity || '-'}}</text>
            </div>
          </cell>
        </list>
      </div>

      <div class="container">
        <div class="td-row">
          <text class="td-serial text-muted">栋号</text>
          <text class="td-text text-muted">时间</text>
          <text class="td-text text-muted">鸡均重(kg)</text>
          <text class="td-text text-muted"
                v-if="isEggChick">蛋均重(g)</text>
        </div>

        <vm-status v-if="showLogStatus"
                   empty-text="暂无日志"
                   :type="logTotalPages === -1 ? 'error' : 'empty'"></vm-status>

        <list ref="awList"
              :showRefresh="true"
              :showLoadMore="showLogLoadMore"
              @refresh="logRefresh('awList')"
              @loadMore="logLoadmore('awList')"
              loadmoreoffset="100">
          <cell v-for="(log, index) in logs"
                :key="index">
            <div class="td-row">
              <text class="td-serial">{{log.house_no}}</text>
              <text class="td-text">{{log.log_time}}</text>
              <text class="td-text">{{log.avg_weight}}</text>
              <text class="td-text"
                    v-if="isEggChick">{{log.egg_avg_weight || '-'}}</text>
            </div>
          </cell>
        </list>
      </div>

    </wxc-tab-page>

    <wxc-popup :show="popupVisible"
               ref="popup"
               @wxcPopupOverlayClicked="popupBeforeClose"
               pos="right"
               :width="480">
      <div class="border-bottom"
           :style="{height: headHeight + 'px'}"></div>
      <div class="p-3 align-center"
           v-if="!columns.length">
        <text class="p-3 text-muted text-center">没有历史批次信息</text>
        <text class="btn"
              @click="hidePopup">确定</text>
      </div>

      <div class="flex"
           v-else>

        <list ref="columnList"
              :showRefresh="true"
              :showLoadMore="showColumnLoadMore"
              @refresh="columnRefresh()"
              @loadMore="columnLoadmore()"
              loadmoreoffset="100">
          <cell v-for="(column, index) in columns"
                :key="index">
            <text class="list-column"
                  @click="onColumnSelect(index)">{{column.enter_batch_no}}</text>
          </cell>
        </list>

      </div>
      <text class="btn"
            style="margin-left: 100px;"
            @click="hidePopup">取消</text>
    </wxc-popup>
  </div>
</template>
<script>
import VmStatus from '../../components/vm-status.vue'
import { WxcPopup, WxcTabPage, Utils } from 'weex-ui'
import { getStyles } from '../../plugins/tab-page-styles'
import {
  STORAGE_FARM
} from '../../plugins/constant'
import {
  CATEGORY_EGG_CHICK
} from '../../plugins/enumChick'

export default {
  components: { WxcPopup, WxcTabPage, VmStatus },
  props: {},
  data() {
    return {
      farm: {},
      tabTitles: [
        { title: '日常管理' },
        { title: '免疫用药' },
        { title: '温度湿度' },
        { title: '均重填写' },
      ],
      tabStyles: getStyles({ width: 187.5 }),
      tabPageHeight: 1334,
      headHeight: +weex.config.eros.statusBarHeight || 52,
      //
      columnParams: {
        index: 1,
        size: 20,
        'supplier_id.eq': ''
      },
      columnTotalPages: 2,
      columns: [],
      columnIndex: -1,
      popupVisible: false,
      //
      logParams: {
        index: 1,
        size: 20,
        'supplier_id.eq': '',
        'purchase_no.eq': ''
      },
      logTotalPages: 2,
      logs: []
    }
  },
  computed: {
    columnSelected() {
      return this.columnIndex > -1 && this.columnIndex < this.columns.length ? this.columns[this.columnIndex] : {}
    },
    showColumnLoadMore() {
      return this.columnTotalPages > this.columnParams.index
    },
    showLogLoadMore() {
      return this.logTotalPages > this.logParams.index
    },
    isEggChick() {
      const cateId = this.columnSelected.output_product_category
      return cateId ? cateId.indexOf(CATEGORY_EGG_CHICK) > -1 : false
    },
    showLogStatus() {
      return this.logTotalPages === -1 || !this.logs.length
    }
  },
  watch: {},
  created() {
    this.tabPageHeight = Utils.env.getPageHeight()
    this.getFarm()
  },
  methods: {
    getFarm() {
      this.farm = this.$storage.getSync(STORAGE_FARM) || {}
      if (this.farm.id) {
        this.columnParams['supplier_id.eq'] = this.farm.id
        this.logParams['supplier_id.eq'] = this.farm.id
        this.columnRefresh(true)
      } else {
        this.$notice.toast({ message: '没有鸡场信息' })
        this.$router.setBackParams({ type: 1 })
      }
    },
    // 批次
    columnRefresh(fetchLog = false) {
      this.columnParams.index = 1
      this.getColumn().then(res => {
        this.columns = res
        if (fetchLog && this.columns.length) {
          this.columnIndex = 0
          this.logRefresh()
        }
      }).finally(() => {
        this.$refs['columnList'].refreshEnd()
      })
    },
    columnLoadmore() {
      this.getColumn().then(res => {
        this.columns.push(...res)
      }).finally(() => {
        this.$refs['columnList'].loadMoreEnd()
      })
    },
    getColumn() {
      return new Promise((resolve, reject) => {
        this.$api.getData({
          server: 'agr_chain',
          table: 'chick_column_view',
          params: this.columnParams
        }).then(res => {
          this.columnParams.index++
          this.columnTotalPages = res && res.totalPages || 0
          const data = res && res.data || []
          resolve(data)
        }).catch(err => {
          this.columnTotalPages = -1
          reject(err)
        })
      })
    },
    showPopup() {
      this.popupVisible = true
    },
    hidePopup() {
      this.$refs['popup'].hide()
    },
    popupBeforeClose() {
      this.popupVisible = false
    },
    onColumnSelect(index) {
      this.columnIndex = index
      this.logRefresh()
      this.hidePopup()
    },
    // 日志
    logRefresh(ref = 'logList') {
      this.logParams.index = 1
      this.getLog().then(res => {
        this.logs = res
      }).finally(() => {
        this.$refs[ref].refreshEnd()
      })
    },
    logLoadmore(ref = 'logList') {
      this.getLog().then(res => {
        this.logs.push(...res)
      }).finally(() => {
        this.$refs[ref].loadMoreEnd()
      })
    },
    getLog() {
      this.logParams['purchase_no.eq'] = this.columnSelected.enter_batch_no
      return new Promise((resolve, reject) => {
        this.$api.getData({
          server: 'agr_chain',
          table: 'base_produce_log_view',
          params: this.logParams
        }).then(res => {
          this.logParams.index++
          this.logTotalPages = res && res.totalPages || 0
          const data = res && res.data || []
          resolve(data.map(item => {
            item.log_time = this.getSubstr(item.log_time)
            item.imm_product_name = this.getNewline(item.imm_product_name)
            item.imm_dosage = this.getNewline(item.imm_dosage)
            item.drug_product_name = this.getNewline(item.drug_product_name)
            item.drug_product_amount = this.getNewline(item.drug_product_amount)
            return item
          }))
        }).catch(err => {
          this.logTotalPages = -1
          reject(err)
        })
      })
    },
    getSubstr(str, start = 0, end = 10) {
      return str ? str.substr(start, end) : ''
    },
    getNewline(str, separator = ',') {
      return str ? str.replace(new RegExp(separator, 'g'), '\n') : ''
    }
  }
}
</script>
<style lang="scss" scoped>
@import "../../css/variables.scss";
$select-border-color: $accent-light;
$select-label-bg: lighten($accent, 45%);

.icon {
  font-family: alicon;
}
.p-2 {
  padding: 20px;
}
.p-3 {
  padding: 30px;
}
.pb-2 {
  padding-bottom: 20px;
}
.pb-3 {
  padding-bottom: 30px;
}
.px-2 {
  padding-left: 20px;
  padding-right: 20px;
}
.mb-1 {
  margin-bottom: 10px;
}
.mb-2 {
  margin-bottom: 20px;
}
.text {
  font-size: 28px;
}
.text-muted {
  color: #999;
}
.text-center {
  text-align: center;
}
.align-center {
  align-items: center;
}
.border-bottom {
  border-bottom-width: 1px;
  border-bottom-color: $border-color;
}
.flex-row {
  flex-direction: row;
}
.flex {
  flex: 1;
}
.bg-light {
  background-color: $border-color;
}
.bg-white {
  background-color: #fff;
}
.container {
  width: 750px;
  align-items: center;
}

.btn {
  width: 300px;
  height: 70px;
  line-height: 70px;
  border-radius: 35px;
  padding-left: 30px;
  padding-right: 30px;
  text-align: center;
  font-size: 28px;
  border-width: 1px;
  border-color: #ddd;
  margin-top: 20px;
  margin-bottom: 20px;
}
.btn:active {
  background-color: #ddd;
}

.log-select {
  margin-top: 20px;
  margin-bottom: 20px;
  border-radius: 6px;
  flex-direction: row;
  align-items: stretch;
  overflow: hidden;
  width: 680px;
  margin-left: 35px;
  background-color: #fff;
}
.log-select-label {
  height: 80px;
  line-height: 80px;
  padding-left: 20px;
  padding-right: 20px;
  font-size: 28px;
  color: $accent;
  border-top-left-radius: 6px;
  border-bottom-left-radius: 6px;
  background-color: $select-label-bg;
  border-left-width: 1px;
  border-left-color: $select-border-color;
  border-top-width: 1px;
  border-top-color: $select-border-color;
  border-bottom-width: 1px;
  border-bottom-color: $select-border-color;
}
.log-select-content {
  flex: 1;
  height: 80px;
  line-height: 80px;
  padding-left: 20px;
  padding-right: 20px;
  text-align: center;
  border-top-width: 1px;
  border-top-color: $select-border-color;
  border-bottom-width: 1px;
  border-bottom-color: $select-border-color;
}
.log-select-icon {
  height: 80px;
  line-height: 80px;
  padding-right: 20px;
  padding-left: 20px;
  color: #999;
  border-top-right-radius: 6px;
  border-bottom-right-radius: 6px;
  border-right-width: 1px;
  border-right-color: $select-border-color;
  border-top-width: 1px;
  border-top-color: $select-border-color;
  border-bottom-width: 1px;
  border-bottom-color: $select-border-color;
}

.log-num {
  font-size: 34px;
}
.log-hint {
  font-size: 24px;
  color: #999;
}

.td-row {
  width: 750px;
  flex-direction: row;
  align-items: center;
  padding-top: 25px;
  padding-bottom: 25px;
  background-color: #fff;
  border-bottom-width: 1px;
  border-bottom-color: $border-color;
}
.td-row:active {
  background-color: #eee;
}
.td-text {
  flex: 1;
  text-align: center;
  font-size: 25px;
}
.td-serial {
  width: 80px;
  text-align: center;
  font-size: 25px;
}

.list-column {
  text-align: center;
  padding: 20px;
  border-bottom-width: 1px;
  border-bottom-color: $border-color;
}
.list-column:active {
  background-color: $border-color;
}
</style>
